package com.pachong.android.baseuicomponent.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;

import com.pachong.android.baseuicomponent.activity.swipeback.SwipeBackActivityHelper;
import com.pachong.android.baseuicomponent.activity.swipeback.SwipeBackable;
import com.pachong.android.baseuicomponent.view.CenterToolbar;
import com.umeng.analytics.MobclickAgent;

import java.util.List;

import butterknife.ButterKnife;


/**
 * 1. Activity定义了许多的状态，用户可以通过set(status)来切换状态，每个状态对应一个View，用户还可以自定义这个View
 * <p>
 * 每个状态对应一个UI 布局,用户可以自定义这些布局,通过setXX方法（e.g setEmptyView）
 * <p>
 * 2. 提供了title的控制,User可以使用以Toolbar,也可自定义自己的tool bar, Activity默认显示toolbar
 *
 * @author Vivi Peng
 * @version 1.0.0
 * @e-mail pengveivei@sina.cn
 * @QQ 897058316
 * @since 1979-01-01
 */
public abstract class BaseActivity extends StateActivity implements SwipeBackable {
    private SwipeBackActivityHelper mSwipeHelper;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setCustomToolbar(new CenterToolbar(this));
        getCustomToolbar().setTitle(getTitle());
        ButterKnife.bind(this);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }


    @Override
    public void setTitle(CharSequence title) {
        super.setTitle(title);
        getCustomToolbar().setTitle(title);
    }

    @Override
    public void setTitle(int titleId) {
        super.setTitle(titleId);
        getCustomToolbar().setTitle(titleId);
    }

    @Override
    public CenterToolbar getCustomToolbar() {
        return (CenterToolbar) super.getCustomToolbar();
    }

    public ImageButton enableBackButton() {
        return getCustomToolbar().enableBackButton();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        if (mSwipeHelper != null)
            mSwipeHelper.onPostCreate();
    }

    @Override
    public View findViewById(int id) {
        View v = super.findViewById(id);
        if (v == null && mSwipeHelper != null)
            return mSwipeHelper.findViewById(id);
        return v;
    }

    @Override
    public void setSwipeBackEnable(boolean enable) {
        if (enable) {
            mSwipeHelper = new SwipeBackActivityHelper(this);
            mSwipeHelper.onActivityCreate();
        }
    }


   /* @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        FragmentManager fm = getSupportFragmentManager();
        int index = requestCode >> 16;
        if (index != 0) {
            index--;
            if (fm.getFragments() == null || index < 0
                    || index >= fm.getFragments().size()) {
                Log.w("BaseActivity", "Activity result fragment index out of range: 0x"
                        + Integer.toHexString(requestCode));
                return;
            }
            Fragment frag = fm.getFragments().get(index);
            if (frag == null) {
                Log.w("BaseActivity", "Activity result no fragment exists for index: 0x"
                        + Integer.toHexString(requestCode));
            } else {
                handleResult(frag, requestCode, resultCode, data);
            }
            return;
        }

    }*/

    /**
     * 递归调用，对所有子Fragement生效
     *
     * @param frag
     * @param requestCode
     * @param resultCode
     * @param data
     */
    private void handleResult(Fragment frag, int requestCode, int resultCode,
                              Intent data) {
        frag.onActivityResult(requestCode & 0xffff, resultCode, data);
        List<Fragment> frags = frag.getChildFragmentManager().getFragments();
        if (frags != null) {
            for (Fragment f : frags) {
                if (f != null)
                    handleResult(f, requestCode, resultCode, data);
            }
        }
    }


    /**
     * 设置刷新的UI是否可以取消
     *
     * @param cancelable
     */
    public void setRefreshingCancelable(final boolean cancelable) {
        getEmptyRefreshingView().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (cancelable) {
                    return false;
                } else {
                    return true;
                }
            }
        });
    }


    protected <V extends View> V findView(int resId) {
        return (V) getDataView().findViewById(resId);
    }

}
